package com.example.glide.slice;

import com.bumptech.glide.Glide;
import com.example.glide.ResourceTable;
import com.example.glide.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.bundle.IBundleManager;

import java.io.File;

public class GlideDownLoadAbilitySlice extends AbilitySlice {

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_down_load_slice_layout);
        findComponentById(ResourceTable.Id_btn_down).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = "https://creditcard.bankcomm.com/tfimg/public00/M00/12/47/trScJ1_3_GaAAzY6AAHXvU3zd8A760.png";
                            File file =
                                    Glide.with(getAbility()).downloadOnly()
                                            .load(url)
                                            .submit()
                                            .get();
                            LogUtil.info("GlideDownLoad", "file:" + file);
                            if (file != null) {
                                showToast("下载成功");
                                return;
                            }
                        } catch (Exception e) {
                            LogUtil.error("GlideDownLoad", "error message:" + e.getMessage());
                        }

                        showToast("下载失败");
                    }
                }).start();
            }
        });
        reqPermissions();
    }

    private void reqPermissions() {
        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission("ohos.permission.READ_USER_STORAGE")) {
                requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE",
                        "ohos.permission.WRITE_USER_STORAGE"}, 1000);
            }
        }
    }

    private void showToast(String str) {
        TaskDispatcher taskDispatcher = getUITaskDispatcher();
        taskDispatcher.delayDispatch(new Runnable() {
            @Override
            public void run() {
                ToastDialog toastDialog = new ToastDialog(getAbility());
                toastDialog.setAlignment(LayoutAlignment.HORIZONTAL_CENTER);
                toastDialog.setContentText(str);
                toastDialog.show();
            }
        }, 10);
    }
}
